{% extends 'baykeshop/base_site.html' %}

{% load static %}

{% block title %}购物车{% endblock %}

{% block extrastyle %}
<script src="{% static 'baykeshop/js/axios.min.js' %}"></script>
<script src="{% static 'baykeshop/js/request.js' %}"></script>
<style>
    .table td {
        vertical-align: middle;
    }
</style>
{% endblock %}
    
{% block breadcrumb %}
<div class="container">
  <nav class="breadcrumb is-marginless mt-3 mb-3 is-small" aria-label="breadcrumbs">
    <ul>
      <li><a href="{% url 'baykeshop:home' %}">首页</a></li>
      <li class="is-active"><a href="#" aria-current="page">购物车</a></li>
    </ul>
  </nav>
</div>
{% endblock %}

{% block content %}
{{ carts|json_script:"carts-data" }}

<div id="cart" class="container">
    <div class="box is-marginless" v-if="carts.length > 0">
        <template>
            <b-table
                checkable
                hoverable
                :is-row-checkable="(row) => Number(row.stock) > Number(row.sales)"
                :checked-rows.sync="checkedRows" 
                :data="carts">
                <b-table-column field="id" label="ID" v-slot="props">
                    {$ props.row.id $}
                </b-table-column>
                
                <b-table-column field="cover_pic" label="商品图" v-slot="props">
                    <figure class="image is-128x128">
                        <b-image
                            :src="`${props.row.cover_pic}`"
                            :alt="props.row.title"
                            ratio="1by1"
                        ></b-image>
                    </figure>
                </b-table-column>

                <b-table-column field="title" label="标题" v-slot="props">
                    {$ props.row.title $}
                    <div class="is-flex">
                        <p class="mt-2 mr-3" v-for="spec, i in props.row.options" :key="i">
                            <span class=" has-text-grey-light">
                                {$ spec.spec__name $}
                            </span>：<strong>{$ spec.name $}</strong> 
                        </p>
                    </div>
                </b-table-column>

                <b-table-column field="stock" label="库存" width="120" v-slot="props">
                    {$ props.row.stock $}
                </b-table-column>

                <b-table-column field="price" label="单价" width="120" v-slot="props">
                    <span class="is-size-5 has-text-grey">¥</span>{$ props.row.price $}
                </b-table-column>

                <b-table-column field="sales" label="数量" v-slot="props">
                    <b-field>
                        <b-numberinput
                            @input="updateNum(props.row)"
                            controls-position="compact"
                            size="is-small"
                            type="is-light"
                            :min="1"
                            :max="props.row.stock"
                            :editable='true'
                            v-model="props.row.sales">
                        </b-numberinput>
                    </b-field>
                </b-table-column>

                <b-table-column field="total_price" label="小计" width="120" v-slot="props">
                    <span class="is-size-5 has-text-grey">¥</span>{$ props.row.total_price $}
                </b-table-column>

                <b-table-column field="caozuo" label="操作" width="80" v-slot="props">
                    <button class="delete" @click="deleteCart(props.row.id)">删除</button>
                </b-table-column>

                <template #footer>
                    <div class="has-background-light is-flex is-align-items-center is-justify-content-space-between">
                        <div class="has-text-danger-dark ml-3">
                            已选<span class="is-size-4 pl-2 pr-2">{$ checkedRows.length $}</span>件商品 
                        </div>
                        <div class=" is-flex is-align-items-center has-text-danger-dark ">
                            <span class="is-size-5">合计：</span> <span class="is-size-3 pr-5">¥ {$ total $}</span>
                            <button class="button is-primary is-radiusless is-large pl-6 pr-6" :disabled="checkedRows.length > 0 ? false : true"
                                v-on:click.capture="cashRegister(checkedRows)">
                                去结算
                            </button>
                        </div>
                    </div>
                </template>
            </b-table>
        </template>
    </div>
    <div class="has-text-centered has-text-danger is-size-5" v-else> 
        <img src="{% static 'baykeshop/img/noCart1.png' %}">
        <p> 亲，购物车还是空的哟~ </p>
        <a class=" button is-primary is-outlined mt-4" href="{% url 'baykeshop:home' %}">继 续 逛</a>
    </div>
</div>

{% endblock %}


{% block vue %}
    <script>
        var carts = JSON.parse(document.getElementById('carts-data').textContent);
        var cart = new Vue({
            el: '#cart',
            delimiters: ['{$', '$}'],
            data: {
                carts: carts,
                checkedRows: [],
                total: 0,
                checkedRowsCartID:''
            },
            created(){
                // 第一次加载时处理库存不足的选中数据
                this.carts.forEach(row => {
                    if (row.stock > row.sales){
                        this.checkedRows.push(row)
                        this.total += parseFloat(row.total_price)
                        this.total = parseFloat(this.total).toFixed(2) 
                    }
                })

            },
            methods:{
                // 修改数量
                updateNum(data){
                    // 数量变化时价格跟随变化
                    data.total_price = parseFloat(data.sales * data.price).toFixed(2)
                    // 数据库修改
                    const sendData = new FormData()
                    sendData.append('num', data.sales)
                    sendData.append('id', data.id)
                    sendData.append('actions', 'update')
                    request({
                        method: 'post',
                        url: `{% url "baykeshop:update_cart" %}`,
                        headers: {'Accept': 'application/json'},
                        data: sendData
                    }).then(res => {
                        if (res.data.code == 'ok') {
                            navbar.toastMessage('is-success', res.data.message)
                            cartNum._data.cart_num = data.sales
                            // location.reload()
                        }else{
                            navbar.toastMessage('is-danger', res.data.message)
                        }
                    })
                },

                // 删除购物车
                deleteCart(id){
                    const sendData = new FormData()
                    sendData.append('id', id)
                    sendData.append('actions', 'delete')
                    this.$buefy.dialog.confirm({
                        message: '是否确认删除该购物车商品！',
                        cancelText: '取消',
                        onConfirm: () => {
                            request({
                                method: 'post',
                                url: `{% url "baykeshop:update_cart" %}`,
                                headers: {'Accept': 'application/json'},
                                data: sendData
                            }).then(res => {
                                if (res.data.code == 'ok') {
                                    navbar.toastMessage('is-success', res.data.message)
                                    location.reload()
                                }else{
                                    navbar.toastMessage('is-danger', res.data.message)
                                }
                            })
                        }
                    })
                    
                },

                // 跳转到结算中心
                cashRegister(rows){
                    let cart_ids = []
                    rows.forEach(element => {
                        cart_ids.push(element.id)
                    })
                    location.href = `{% url 'baykeshop:cash_register' %}?cartsID=${cart_ids.join()}`
                }
            },
            watch: {
                // 监听选中商品
                checkedRows: {
                    handler: function (rows, oldrows) {
                        let total = 0;
                        rows.forEach(row => {
                            total += parseFloat(row.total_price)
                        })
                        this.total = total.toFixed(2)
                    },
                    deep: true
                },

                // 监听数量变化

            }
        })
    </script>
{% endblock %}
    
    
    